package com.raylu.util

import com.raylu.bean.{DauInfo, PageLog, Person}

import java.lang.reflect.{Field, Modifier}
import scala.util.control.Breaks.{break, breakable}

/**
 *
 * Description:
 *
 * Create by lucienoz on 2021/11/30.
 * Copyright © 2021 lucienoz. All rights reserved.
 */
object MyBeanUtil {

	def main(args : Array[String]) : Unit = {
		val a : Person = Person ( "a", 30 )
		val b : Person = Person ( "sad", 28 )
				copyProperties(a,b)
//		val xx : Person = Person ( "xx", 26 )
//		xx.age=27
		println ( b.toString )
		val pageLog : PageLog = PageLog ( ar = "11", ba = null, ch = null, isNew = null, md = null, mid = null, os = null, uid = null, vc = null, ts = 0L, duringTime = null, lastPageId = null, pageId = null )
		val dauInfo : DauInfo = DauInfo ( ar = null, ba = null, ch = null, isNew = null, md = null, mid = null, os = null, uid = null, vc = null, ts = 0L, duringTime = null, lastPageId = null, pageId = null, user_gender = null, user_age = null, province_name = null, province_iso_code = null, province_3166_2 = null, province_area_code = null, dt = null, hr = null )

		copyProperties(pageLog,dauInfo)

		println ( dauInfo.toString )
		
		
	}


	def copyProperties(obj : Object, toObj : Object) : Unit = {
		if (obj == null) {
			return
		}
		val fields : Array[Field] = toObj.getClass.getDeclaredFields ()
		for (field <- fields) {
			field.setAccessible ( true )
			breakable {
				if (Modifier.isFinal ( field.getModifiers () )) break
				//判断字段名称和字段类型是否相同

				val toObjFieldName : String = field.getName
				val toObjFieldType : String = field.getType.toString
				var objField : Field = null
				try {
					objField = obj.getClass.getDeclaredField ( toObjFieldName )
				} catch {
					case e:NoSuchFieldException => break()
					case e => e.printStackTrace()
				}
				objField.setAccessible(true)
				if (objField==null) break()
				if(objField.getType.toString!=toObjFieldType || objField.getName!=toObjFieldName) break()
				val objFieldValue : AnyRef = objField.get ( obj )
				field.set(toObj,objFieldValue)




			}
		}


	}

}
